<template>
	<el-dialog title="提示" :visible.sync="$store.state.Users.revise" width="36%">
		<!-- 表单验证组件 -->
		<el-form
			ref="ruleForm"
			label-width="100px"
			class="demo-ruleForm"
			:model="ruleForm"
			:rules="rules"
		>
			<el-form-item label="用户名" prop="username">
				<el-input v-model="ruleForm.username" disabled></el-input>
			</el-form-item>
			<el-form-item label="邮箱" prop="email">
				<el-input v-model="ruleForm.email"></el-input>
			</el-form-item>
			<el-form-item label="手机" prop="modile">
				<el-input v-model="ruleForm.modile"></el-input>
			</el-form-item>
		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="dialogVisible">取 消</el-button>
			<el-button type="primary" @click="dialogVisibled">确 定</el-button>
		</span>
	</el-dialog>
</template>
<script>
export default {
	name: 'Revise',

	data() {
		var checkEmail = (rule, value, callback) => {
			const regEmail =

				/^([a-zA-Z]|[0-9])(\w)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/

			if (!value) {
				return callback(new Error('邮箱不能为空'))
			}
			if (regEmail.test(value)) {
				return callback()
			}
			callback(new Error('邮箱格式错误'))
		}
		var checkMobile = (rule, value, callback) => {
			const regEmail = /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/
			if (!value) {
				return callback(new Error('手机号不能为空'))
			}
			if (regEmail.test(value)) {
				return callback()
			}
			callback(new Error('手机号格式错误'))
		}
		return {
			id: '',
			ruleForm: {
				username: '',
				email: '',
				modile: '',
			},
			rules: {
				email: [{ validator: checkEmail, trigger: 'blur' }],
				modile: [{ validator: checkMobile, trigger: 'blur' }],
			},
		}
	},

	methods: {
		dialogVisible() {
			this.$store.commit('Users/Revise')
		},
		dialogVisibled() {
			this.$refs.ruleForm.validate(boolean => {
				if (boolean) {
					this.$http
						.put(`users/${this.id}`, {
							email: this.ruleForm.email,
							mobile: this.ruleForm.modile,
						})
						.then(response => {

							const { meta} = response.data

							if (meta.status == 200) {
								this.$message({
									type: 'success',
									message: '修改成功！',
								})
								this.$bus.$emit('update')
							} else {
								this.$message.error('修改失败！')
							}
						})
						.catch(error => {
							console.log(error.message)
						})
				} else {
					this.$message.error('修改失败！')
				}
			})

			this.$store.commit('Users/Revise')
		},
	},
	components: {},
	mounted() {},
	created() {
		this.$bus.$on('reviseData', data => {
			this.id = data.id
			this.$nextTick(() => {

				this.ruleForm.username = data.username
				this.ruleForm.email = data.email
				this.ruleForm.modile = data.mobile
			})
		})
	},
}
</script>
